package com.wcs.shortlink.admin.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.fastjson2.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wcs.shortlink.admin.common.convention.exception.ClientException;
import com.wcs.shortlink.admin.dao.entity.UserDO;
import com.wcs.shortlink.admin.dao.mapper.UserMapper;
import com.wcs.shortlink.admin.dto.req.UserLoginReqDTO;
import com.wcs.shortlink.admin.dto.req.UserRegisterReqDTO;
import com.wcs.shortlink.admin.dto.req.UserUpdateReqDTO;
import com.wcs.shortlink.admin.dto.resp.UserLoginRespDTO;
import com.wcs.shortlink.admin.dto.resp.UserRespDTO;
import com.wcs.shortlink.admin.service.UserService;
import lombok.RequiredArgsConstructor;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

import static com.wcs.shortlink.admin.common.constant.RedisCacheConstant.LOCK_USER_REGISTER_KEY;
import static com.wcs.shortlink.admin.common.enums.UserErrorCodeEnum.*;

/**
 * 用户接口实现层
 */
@Service
@RequiredArgsConstructor
public class UserServiceImpl extends ServiceImpl<UserMapper, UserDO> implements UserService {

    //布隆过滤器
    private final RBloomFilter<String> userRegisterCachePenetrationBloomFilter;

    private final RedissonClient redissonClient;

    private final StringRedisTemplate stringRedisTemplate;

    @Override
    public UserRespDTO getUserByUsername(String username) {
        LambdaQueryWrapper<UserDO> queryWrapper =
                Wrappers.lambdaQuery(UserDO.class)
                        //添加查询条件，相当于 SQL 中的 WHERE username = ?
                        .eq(UserDO::getUsername, username);
        //selectOne(queryWrapper)：根据查询条件返回一条记录，如果查询到多条会抛出异常。
        UserDO userDO = baseMapper.selectOne(queryWrapper);
        //复制属性
        UserRespDTO result = new UserRespDTO();
        if(userDO != null) {
            BeanUtils.copyProperties(userDO, result);
            return result;
        } else {
            return null;
        }
    }

    /**
     * 使用布隆过滤器改进
     */
    @Override
    public Boolean availableUsername(String username) {
        return !userRegisterCachePenetrationBloomFilter.contains(username);
    }

    @Override
    public void register(UserRegisterReqDTO requestParam) {

        if(!availableUsername(requestParam.getUsername())) {
            throw new ClientException(USER_NAME_EXIST);
        }

        RLock lock = redissonClient.getLock(LOCK_USER_REGISTER_KEY + requestParam.getUsername());

        try {
            if(lock.tryLock()){
                int inserted = baseMapper.insert(BeanUtil.toBean(requestParam, UserDO.class));
                if(inserted < 1) {
                    throw new ClientException(USER_SAVE_ERROR);
                }
                userRegisterCachePenetrationBloomFilter.add(requestParam.getUsername());
                return;
            }
            throw new ClientException(USER_NAME_EXIST);
        } finally {
            lock.unlock();
        }
    }

    @Override
    public void update(UserUpdateReqDTO requestParam) {

        //TODO 验证当前用户名是否为当前用户
        LambdaUpdateWrapper<UserDO> updateWrapper = Wrappers.lambdaUpdate(UserDO.class).eq(UserDO::getUsername, requestParam.getUsername());
        baseMapper.update(BeanUtil.toBean(requestParam, UserDO.class),updateWrapper);

    }

    @Override
    public UserLoginRespDTO login(UserLoginReqDTO requestParam) {

        //用户名密码都要存在 并且没有注销
        LambdaQueryWrapper<UserDO> queryWrapper = Wrappers.lambdaQuery(UserDO.class)
                .eq(UserDO::getUsername, requestParam.getUsername())
                .eq(UserDO::getPassword, requestParam.getPassword())
                .eq(UserDO::getDelFlag, 0);

       UserDO userDO =  baseMapper.selectOne(queryWrapper);
       if (userDO == null) {

           throw new ClientException(USER_NOT_EXIST);
       }
       Boolean hasLogin =  stringRedisTemplate.hasKey("login_" + requestParam.getUsername());
       if(hasLogin != null && hasLogin) {
            throw new ClientException("用户已登录");
        }

        /**
         * Hash 结构
         * key login_用户名
         * Value
         *  key：token标识
         *  val：json字符串 用户信息
         */

        String uuid = UUID.randomUUID().toString();

        stringRedisTemplate.opsForHash().put("login_"+requestParam.getUsername(),uuid,JSON.toJSONString(userDO));

        //设置过期时间
        stringRedisTemplate.expire("login_"+requestParam.getUsername(),30L, TimeUnit.DAYS);

        return new UserLoginRespDTO(uuid);
    }

    @Override
    public Boolean checkLogin(String username,String token) {
        return stringRedisTemplate.opsForHash().get("login_"+username,token)!=null;
    }

    @Override
    public void logout(String username, String token) {
        if(checkLogin(username,token)) {
            stringRedisTemplate.delete("login_"+username);
            return;
        }
        throw new ClientException("用户信息不正确");
    }
}
